package com.aitesting.controller;


import com.aitesting.common.CommonResult;
import com.aitesting.model.Task;
import com.aitesting.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 任务管理
 * @author zz
 * @since 2022-02-20
 */
@Slf4j
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;

    /**
     * 根据id查询任务
     * @param id 任务id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public CommonResult<Task> getById(@PathVariable("id") Integer id) {
        return CommonResult.success(taskService.getById(id));
    }

    /**
     * 查询所有任务
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public CommonResult<Task> getList() {
        return CommonResult.success(taskService.list());
    }

    /**
     * 新增任务
     * @param task 任务对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResult<Task> create(@RequestBody Task task){
        boolean isOk = taskService.save(task);
        if (isOk) {
            return CommonResult.success(task);
        }else {
            log.error("新增任务失败,数据不合法 {}", task);
            return CommonResult.failed();
        }
    }

    /**
     * 根据id删除任务
     * @param id 任务id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public CommonResult<Task> delete(@PathVariable Integer id) {
        boolean isOk = taskService.removeById(id);
        if (isOk) {
            return CommonResult.success(null);
        }else {
            return CommonResult.failed();
        }
    }

    /**
     * 根据id更新任务信息
     * @param task 任务对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public CommonResult<Task> update(@RequestBody Task task) {
        boolean isOk = taskService.updateById(task);
        if (isOk) {
            return CommonResult.success(task);
        }else {
            log.error("更新任务失败,数据不合法 {}", task);
            return CommonResult.failed();
        }
    }
}

